package api

import (
	"blog/library"
	"blog/models"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type AdminController struct {
	baseController
}

type AdminForm struct {
	Id       int
	Account  string
	Password string
}

func (a *AdminController) List() {
	page, _ := a.GetInt("page", 1)
	limit, _ := a.GetInt("limit", 1)
	list, row, err := models.GetList(models.AdminTable(), page, limit, &orm.Condition{}, "-Id")
	if err != nil {
		beego.Error(err.Error())
	}

	a.NewApi().Pagination(row).Success(list)
}

func (a *AdminController) Create() {
	admin := models.NewAdmin()
	if err := a.LoadData(admin); err != nil {
		a.NewApi().Error(err.Error())
	}
	if models.Exist(models.AdminTable(), orm.NewCondition().And("account", admin.Account)) {
		a.NewApi().Error("该账号已存在")
	}
	admin.Password = library.Md5(admin.Password)

	if _, err := models.Create(admin); err != nil {
		a.NewApi().Error(err.Error())
	}
	a.NewApi().Success([]int{})
}

func (a *AdminController) Update() {
	admin := models.NewAdmin()
	if err := a.LoadData(admin); err != nil {
		a.NewApi().Error(err.Error())
	}

	id, _ := a.GetInt("id", -1)
	if admin.Id == 0 {
		a.NewApi().Error("id错误")
	}

	if _, err := models.UpdateByCondition(admin); err != nil {
		a.NewApi().Error(err.Error())
	}
	a.NewApi().Success(id)
}

func (a *AdminController) Delete() {
	admin := models.NewAdmin()
	if err := a.LoadData(admin); err != nil {
		a.NewApi().Error(err.Error())
	}
	if admin.Id == 0 {
		a.NewApi().Error("id错误")
	}

	if !models.Exist(models.AdminTable(), orm.NewCondition().And("id", admin.Id)) {
		a.NewApi().Error("该id不存在")
	}

	if _, err = models.DeleteById(models.AdminTable(), admin.Id); err != nil {
		a.NewApi().Error("删除失败，请重试")
	}
	a.NewApi().Success([]int{})
}
